package com.alcatel_lucent.osp.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by guoshunw on 2014/10/9.
 */
public class OSPLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    private static Logger log = LoggerFactory.getLogger(OSPLdapAuthoritiesPopulator.class);

    private String rolePrefix = "ROLE_";
    private boolean convertToUpperCase = true;

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {

        log.info("userData={}, username = {}", userData, username);
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

        Set<String> userRoles = new HashSet<String>(Arrays.asList("USER", "ADMIN"));

        for (String role : userRoles) {
            if (convertToUpperCase) {
                role = role.toUpperCase();
            }
            authorities.add(new SimpleGrantedAuthority(rolePrefix + role));
        }
        return authorities;
    }
}
